package BankDemo;

public class Banks implements Runnable {
   //成员
    int money;

    public void setMoney(int n){
        this.money = n;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        //save money
        if (name.equals("会计")){
            saveOrTake(300);
        }
        //take money
        else if(name.equals("出纳")){
            saveOrTake(50);
        }
    }
    //同步方法
    public synchronized void saveOrTake(int account){
        String name = Thread.currentThread().getName();
        //save money
        if (name.equals("会计")){
            for(int i=0;i<3;i++){
                money+=account/3;
                System.out.println(Thread.currentThread().getName()+"存入"+account/3+",账户上有"+money+"元，休息一下");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            /*money+=account;
            System.out.println("成功充值"+account+"元! 总金额为:"+money);*/
        }
        //take money
        else if(name.equals("出纳")){
            for(int i=0;i<3;i++){
                money-=account/3;
                System.out.println(Thread.currentThread().getName()+"取出"+account/3+",账户上有"+money+"元，休息一下");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
